package com.jhg.drgclinicalpathway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jhg.drgclinicalpathway.MyProperties;
import com.jhg.drgclinicalpathway.dao.*;
import com.jhg.drgclinicalpathway.domain.*;
import com.jhg.drgclinicalpathway.service.FormWordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.TreeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@Api("通用API")
@RequestMapping("api")
@Slf4j(topic = "ApiController")
public class ApiController {
    @GetMapping("test")
    public String test() {
        return "SUCCESS";
    }

    @Autowired
    CommonDao dao;

    @ApiOperation("通过病人ID获取")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "病人ID"),
            @ApiImplicitParam(name = "lid", value = "路径ID")
    })
    @GetMapping("pcbyid")
    public RpnMsg pcbyid(String id, Integer lid) {
        List<Map<String, Object>> ls = dao.pcbyid(id, lid);
        return RpnMsg.SUCCESS(ls);
    }


    /**
     * @param proType
     * @param proSubType
     * @param discode
     * @param s
     * @return
     */
    @GetMapping("auto-name")
    public RpnMsg getProType(
            @RequestParam("proType") String proType,
            @RequestParam(value = "proSubType", defaultValue = "") String proSubType,
            @RequestParam(value = "discode", defaultValue = "") String discode,
            @RequestParam("s") String s
    ) {
        if (!StringUtils.isEmpty(s)) {
            s = s.replaceAll("[']", "''");
        }
        List<Map<String, Object>> ls = dao.autoName2(proType, s);
        return RpnMsg.SUCCESS(ls);
    }

    /***
     * 根据诊疗项目id获取收费项目目录
     * @param zlid
     * @return
     */
    @GetMapping("auto-sfxm")
    public RpnMsg getSfxmml(@RequestParam("zlid") String zlid, @RequestParam("lb") String zllb) {
        List<Map<String, Object>> ls = null;
        if ("药品".equals(zllb)) {
            ls = dao.ypxmByZlid(zlid, zllb);
        } else if ("耗材".equals(zllb)) {
            ls = dao.ypxmByZlid(zlid, zllb);
        } else {
            ls = dao.sfxmByZlid(zlid, zllb);
        }
        return RpnMsg.SUCCESS(ls);
    }

    @GetMapping("auto-project")
    public RpnMsg autoProject(
            @RequestParam("proType") String proType,
            @RequestParam("proSubType") String proSubType,
            @RequestParam("s") String s
    ) {
        List<Map<String, Object>> ls = dao.autoProject(proType, proSubType, s);
        return RpnMsg.SUCCESS(ls);
    }


    @Autowired
    Dis2PathwayDao dis2PathwayDao;

    /**
     * 获取项目大类
     *
     * @param code
     * @return
     */
//    @Cacheable(cacheNames = "getProType",key = "#code")
    @GetMapping("getProType")
    public RpnMsg getProType(
            @RequestParam(defaultValue = "") String code,
            @RequestParam(defaultValue = "") String tid
    ) {

        List<String> ls = new ArrayList<String>() {
            {
                add("");
            }
        };
        QueryWrapper<Dis2Pathway> queryWrapper = new QueryWrapper<Dis2Pathway>();
        queryWrapper.eq("疾病编码", code);

        int wayid = 0;
        List<Dis2Pathway> dis2Pathways = dis2PathwayDao.selectList(queryWrapper);
        if (dis2Pathways.size() > 0) {
            wayid = dis2Pathways.get(0).getWayid();
        }
        List<Map<String, Object>> proType2 = dao.getProType2(code, true);
        JSONObject o = new JSONObject();
        o.put("ls", proType2);
        o.put("all", proType2);
        ;
        o.put("pathWay", wayid);

        return RpnMsg.SUCCESS(o);
    }

    @GetMapping("auto-proType")
    public RpnMsg autoProType(@RequestParam(defaultValue = "") String n) {
        n = n.replaceAll("[']", "''");
        List<Map<String, Object>> maps = dao.autoProType(n);
        return RpnMsg.SUCCESS(maps);
    }


    @Autowired
    Pathway2DayCostDao pathway2DayCostDao;

    /**
     * LJ_路径项目天数费用参考
     *
     * @param pid   路径ID
     * @param pcode 项目ID
     * @return
     */
    @GetMapping("pathway2cost")
    public RpnMsg pathway2cost(Integer pid, String pcode) {

        QueryWrapper<Pathway2DayCost> queryWrapper = new QueryWrapper<Pathway2DayCost>();
        queryWrapper.eq("路径ID", pid);
        queryWrapper.eq("项目ID", pcode);
        List<Pathway2DayCost> pathway2DayCosts = pathway2DayCostDao.selectList(queryWrapper);
        return RpnMsg.SUCCESS(pathway2DayCosts);
    }

    @Autowired
    Pro2CostDao pro2CostDao;

    /**
     * LJ_项目费用参考
     *
     * @param id
     * @return
     */
    @GetMapping("pro2cost")
    public RpnMsg pro2cost(String id) {
        QueryWrapper<Pro2Cost> queryWrapper = new QueryWrapper<Pro2Cost>();
        queryWrapper.eq("项目ID", id);
        List<Pro2Cost> pro2Costs = pro2CostDao.selectList(queryWrapper);
        if (pro2Costs.size() > 0) {
            return RpnMsg.SUCCESS(pro2Costs.get(0));
        }
        return RpnMsg.SUCCESS();

    }


    @Autowired
    PathTplDao pathTplDao;

    @Autowired
    PathTplMetaDao pathTplMetaDao;

    @Autowired
    PathTplDataDao pathTplDataDao;

    @Autowired
    ClinicalpathwaydetailDao clinicalpathwaydetailDao;

    @Autowired
    ClinicalpathwaydetailBatchDao clinicalpathwaydetailBatchDao;

    @Autowired
    Clinicalpathwaydetail2Dao clinicalpathwaydetail2Dao;

    @Autowired
    LJ临床路径版本Dao LJ临床路径版本Dao;

    @Autowired
    LJ临床路径明细从表Dao lj临床路径明细从表Dao;

    /*********
     * 保存路径模板
     * @return
     */
    @PostMapping("save-tpl")
    public RpnMsg saveTpl(@RequestBody Map<String, Object> map) throws Exception {

        PathTpl tpl = new PathTpl();
        org.apache.commons.beanutils.BeanUtils.populate(tpl, (Map) map.get("tpl"));

        List<Map<String, Object>> metasMap = (List<Map<String, Object>>) map.get("metas");
        String ctime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        List<PathTplMeta> metas = new ArrayList<>();
        for (Map<String, Object> map1 : metasMap) {
            PathTplMeta meta = new PathTplMeta();
            org.apache.commons.beanutils.BeanUtils.populate(meta, map1);
            metas.add(meta);
        }

        List<PathTplData> data = new ArrayList<>();
        List<String> proNames = new ArrayList<>();
        List<Map<String, Object>> dataMap = (List<Map<String, Object>>) map.get("data");
        for (Map<String, Object> map1 : dataMap) {
            PathTplData d = new PathTplData();
            org.apache.commons.beanutils.BeanUtils.populate(d, map1);

            if (!StringUtils.isEmpty(d.getName())) {
                proNames.add(d.getName());
            }

            if (!StringUtils.isEmpty(d.getProSubType())) {
                proNames.add(d.getProSubType());
            }

            data.add(d);
        }


        //获取项目ID

        List<V临床路径项目> 通过名称获取项目编码 = dao.通过名称获取项目编码(proNames);

        FuncTow<String, String, Boolean, String> 获取小分类项目ID = (proSubType, p, isName) -> {


            if (StringUtils.isEmpty(p)) return "";


            if (isName) {
                List<V临床路径项目> ts = 通过名称获取项目编码.stream().filter(it -> it.get说明().equalsIgnoreCase(proSubType) && p.equalsIgnoreCase(it.get名称())).collect(Collectors.toList());
                if (ts.size() > 0) {
                    return ts.get(0).getId();
                }

                ts = 通过名称获取项目编码.stream().filter(it -> p.equalsIgnoreCase(it.get名称())).collect(Collectors.toList());
                if (ts.size() > 0) {
                    return ts.get(0).getId();
                }

                return "";
            } else {
                List<V临床路径项目> ts = 通过名称获取项目编码.stream().filter(it -> p.equalsIgnoreCase(it.get名称()) && (StringUtils.isEmpty(it.get上级ID()) || it.get上级ID().equalsIgnoreCase("0"))).collect(Collectors.toList());

                if (ts.size() > 0) {
                    return ts.get(0).getId();
                }
                ts = 通过名称获取项目编码.stream().filter(it -> p.equalsIgnoreCase(it.get说明())).collect(Collectors.toList());
                if (ts.size() > 0) {
//                    if(ts.get(0).get名称().equals(ts.get(0).get说明())){
//                        return ts.get(0).getId();
//                    }
                    if (StringUtils.isEmpty(ts.get(0).get上级ID())) return ts.get(0).getId();

                    return ts.get(0).get上级ID();
                }
            }


//            List<V临床路径项目> ts = 通过名称获取项目编码.stream().filter(it -> p.equals(it.get名称())&&it.get说明().equals(proSubType)).collect(Collectors.toList());
//
//            if(isName){
//
//                Arrays.toString(ts.toArray());
//                if(ts.size()>0){
//                    return ts.get(0).getId();
//                }
//
//                return "";
//            }

//            ts = 通过名称获取项目编码.stream().filter(it -> p.equals(it.get名称()) &&
//                    (it.get上级ID().equals("0") || StringUtils.isEmpty(it.get上级ID()))).collect(Collectors.toList());
//            if(ts.size()>0){
//                return ts.get(0).getId();
//            }
//
//            ts = 通过名称获取项目编码.stream().filter(it -> p.equals(it.get说明())).collect(Collectors.toList());
//
//            if(ts.size()>0){
//                if(StringUtils.isEmpty(ts.get(0).get上级ID())) return ts.get(0).getId();
//
//                return ts.get(0).get上级ID();
//            }

            return "";
        };

//        项目编码MAPLs.forEach((it)->{
//            String key = it.get("key");
//            String value = it.get("value");
//            项目编码MAP.put(key,value);
//        });


        for (PathTplData datum : data) {

            if (!StringUtils.isEmpty(datum.getName())) {
                datum.setObjid(获取小分类项目ID.get(datum.getProSubType(), datum.getName(), true));
            }
            if (!StringUtils.isEmpty(datum.getProSubType())) {
                datum.setObjid(获取小分类项目ID.get(datum.getProSubType(), datum.getProSubType(), false));
            }
        }
        boolean isNew = StringUtils.isEmpty(tpl.getId());
        if (StringUtils.isEmpty(tpl.getId())) {
            isNew = true;
        } else {
            PathTpl exists = pathTplDao.selectById(tpl.getId());
            isNew = exists == null;
        }
        tpl.set最近修改日期(ctime);
        if (isNew && StringUtils.isEmpty(tpl.getId())) {
            tpl.setId(UUID.randomUUID().toString());
        }

//        if(StringUtils.isEmpty(tpl.get分组编码())){
//            return RpnMsg.FAIL("分组编码不能为空！");
//        }


//
//        List<String> 适用疾病LS = metas.stream().filter(it -> it.get备注().equals("适用疾病")).map(it -> it.get字段名称()).collect(Collectors.toList());
//
//
//        String codePrefix=tpl.get分组编码().substring(0,1);

//        if(适用疾病LS.size()>0){
//            List<KeyVal> keyVals = pathTplMetaDao.check适用疾病(tpl.getId(), 适用疾病LS);
//
//            if(keyVals.size()>0){
//                //确定当前疾病没有被用于第二个模板
//
//                List<KeyVal> collect2 = keyVals.stream().filter(it -> it.getK2().toString().equals(tpl.get分组编码())).collect(Collectors.toList());
//
//                //已经有相同编码的用过这个编码啦
//                if(collect2.size()==keyVals.size()){
//                    List<String> collect = collect2.stream().map(it -> it.getK1().toString()).collect(Collectors.toList());
//                    return RpnMsg.FAIL("已经有模板使用："+String.join("、",collect)+",请重新设置“应用于以下疾病”");
//                }
//
//                //前缀检查
//                List<KeyVal> collect = keyVals.stream().filter(m ->!m.getK2().toString().startsWith(codePrefix)).collect(Collectors.toList());
//                if(collect.size()>0){
//                    return RpnMsg.FAIL("已经有模板使用："+String.join("、",
//                            collect.stream().map(it->it.getK1().toString())
//                                    .collect(Collectors.toList()))+",请重新设置“应用于以下疾病”");
//                }
//
//            }
//        }

        if (isNew) {
            //tpl.setId(UUID.randomUUID().toString());
            tpl.set创建日期(ctime);
            pathTplDao.insert(tpl);

            for (PathTplMeta meta : metas) {

                meta.set模板ID(tpl.getId());
                pathTplMetaDao.insert(meta);
            }

            for (PathTplData datum : data) {
                datum.set模板ID(tpl.getId());
                pathTplDataDao.insert(datum);
            }
        } else {
            pathTplDao.updateById(tpl);

            QueryWrapper<PathTplData> queryWrapper = new QueryWrapper<PathTplData>();
            queryWrapper.eq("模板ID", tpl.getId());

            QueryWrapper<PathTplMeta> queryWrapper1 = new QueryWrapper<PathTplMeta>();
            queryWrapper1.eq("模板ID", tpl.getId());
            pathTplDataDao.delete(queryWrapper);
            pathTplMetaDao.delete(queryWrapper1);

            for (PathTplMeta meta : metas) {
                meta.set模板ID(tpl.getId());
                pathTplMetaDao.insert(meta);
            }


            for (PathTplData datum : data) {
                datum.set模板ID(tpl.getId());
                pathTplDataDao.insert(datum);
            }

        }

        //=============以下为杨波需要处理的数据========
        //1.通过疾病编码获取路径ID

        QueryWrapper<Clinicalpathwaydetail> clinicalpathwaydetailQueryWrapper = new QueryWrapper<Clinicalpathwaydetail>();
        clinicalpathwaydetailQueryWrapper.eq("版本ID", tpl.getId());
        clinicalpathwaydetailDao.delete(clinicalpathwaydetailQueryWrapper);

        Integer wayid = 0;
        if (!StringUtils.isEmpty(tpl.get路径ID())) {
            wayid = Integer.parseInt(tpl.get路径ID());
        }
//        QueryWrapper<Dis2Pathway> dis2PathwayQwrapper = new QueryWrapper<Dis2Pathway>();
//        dis2PathwayQwrapper.eq("疾病编码",tpl.get疾病编码());
//        List<Dis2Pathway> dis2Pathways = dis2PathwayDao.selectList(dis2PathwayQwrapper);
//        if(dis2Pathways.size()>0){
//            wayid=dis2Pathways.get(0).getWayid();
//        }
        List<Clinicalpathwaydetail> clinicalpathwaydetails = new TreeList();

        Func2<String, Clinicalpathwaydetail> machedFunc = (xm) -> {
            List<Clinicalpathwaydetail> 小分类Ls = clinicalpathwaydetails
                    .stream()
                    .filter(it -> it.get项目id().equals(xm))
                    .collect(Collectors.toList());
            if (小分类Ls.size() == 0) return null;
            return 小分类Ls.get(0);
        };

        for (PathTplData datum : data) {
            Clinicalpathwaydetail detail = new Clinicalpathwaydetail();
            detail.setId(UUID.randomUUID().toString());
            detail.set路径ID(wayid);
            detail.set序号(datum.getXh());
            detail.set小分类(datum.getProSubType());
            detail.set版本ID(tpl.getId());
            detail.set备注(datum.getMark());
            detail.set执行性质((datum.getRqd() == null || datum.getRqd() == false) ? 0 : 1);
            detail.set名称(datum.getName());
            detail.set大分类(datum.getProType());
            detail.set项目id(获取小分类项目ID.get("", datum.getProSubType(), false));

            boolean isName = !StringUtils.isEmpty(datum.getName());

            //TODO:如果有了相关的项目ID并且没有填细项，跳过去重
            Clinicalpathwaydetail preDetail = machedFunc.get(detail.get项目id());

            if (!isName && (preDetail != null)) {
                continue;
            }
            if (isName) {
                String 项目id = 获取小分类项目ID.get(datum.getProSubType(), datum.getName(), isName);
                Clinicalpathwaydetail tDetail = machedFunc.get(项目id);
                if (tDetail != null) {
                    detail.set项目id(项目id);
                    detail.set上级ID(tDetail.getId());
                } else {
                    if (!项目id.equals(detail.get项目id())) {
                        //detail.set项目id(项目id);
                        //新建一个小分类
                        detail.set项目id(项目id);
                        Clinicalpathwaydetail copyObj = JSON.parseObject(JSON.toJSONString(detail), Clinicalpathwaydetail.class);
                        Clinicalpathwaydetail clinicalpathwaydetail = machedFunc.get(获取小分类项目ID.get("", datum.getProSubType(), false));
                        if (clinicalpathwaydetail == null) {
                            copyObj.set项目id(获取小分类项目ID.get("", datum.getProSubType(), false));
                            copyObj.setId(UUID.randomUUID().toString());
                            copyObj.set名称(null);
                            copyObj.set序号(-10);
                            detail.set上级ID(copyObj.getId());
                            clinicalpathwaydetails.add(copyObj);
                        } else {
                            detail.set上级ID(clinicalpathwaydetail.getId());
                        }


                    }
                }
            }
//            if(!StringUtils.isEmpty(datum.getName())){
//
//
//               String 项目id=获取小分类项目ID.get("",datum.getProSubType(),false);
//
//                detail.set项目id(获取小分类项目ID.get(datum.getProSubType(),datum.getName(),true));
//
//
//                String final项目id = 项目id;
//                List<Clinicalpathwaydetail> 小分类Ls = clinicalpathwaydetails
//                        .stream()
//                        .filter(it -> datum.getProType().equals(it.get大分类())
//                                &&it.get项目id().equals(final项目id))
//                        .collect(Collectors.toList());
//
//                if(小分类Ls.size()>0){
//                    detail.set上级ID(小分类Ls.get(0).getId());
//                }else{
//
//                    Clinicalpathwaydetail copyObj = JSON.parseObject(JSON.toJSONString(detail), Clinicalpathwaydetail.class);
//                    copyObj.set项目id(获取小分类项目ID.get("",datum.getProSubType(),false));
//                    copyObj.setId(UUID.randomUUID().toString());
//                    detail.set上级ID(copyObj.getId());
//                    copyObj.set名称(null);
//                    copyObj.set序号(-10);
//                    clinicalpathwaydetails.add(copyObj);
//                }
//            }

            Clinicalpathwaydetail clinicalpathwaydetail = machedFunc.get(detail.get项目id());
            if (clinicalpathwaydetail == null) clinicalpathwaydetails.add(detail);


        }
        //处理组合项

        if (metas.stream().filter(it -> it.get备注().equals("合并项目组")).count() > 0) {
            PathTplMeta meta = metas.stream().filter(it -> it.get字段名称().equals("rqdMergeCells")).findFirst().get();
            JSONObject o = JSON.parseObject(meta.get字段值(), JSONObject.class);
            Set<String> keySet = o.keySet();
            for (String s : keySet) {
                JSONObject point = o.getJSONObject(s);
                JSONObject start = point.getJSONObject("start");
                JSONObject end = point.getJSONObject("end");
                Integer startRow = start.getInteger("row") + 1;
                Integer endRow = end.getInteger("row") + 1;

                clinicalpathwaydetails.stream()
                        .filter(it -> it.get序号() >= startRow && it.get序号() <= endRow)
                        .forEach(it -> {
                            it.set组号(s);
                        });

            }

        }


        for (int i = 0; i < clinicalpathwaydetails.size(); i++) {
            clinicalpathwaydetails.get(i).set序号(i + 1);
            if (StringUtils.isEmpty(clinicalpathwaydetails.get(i).get项目id())) {
                clinicalpathwaydetails.get(i).set项目id("none");
            }
            clinicalpathwaydetailDao.insert(clinicalpathwaydetails.get(i));
        }

        LJ临床路径版本 lj临床路径版本 = LJ临床路径版本Dao.selectById(tpl.getId());
        boolean isNew2 = (lj临床路径版本 == null);
        if (isNew2) {
            lj临床路径版本 = new LJ临床路径版本() {
                {
                    setId(tpl.getId());

                }
            };
            lj临床路径版本.set创建时间(new Date());
            lj临床路径版本.set标准床日(0);
            lj临床路径版本.set标准金额(0.0);
            lj临床路径版本.set版本号("标准版本");
            lj临床路径版本.set版本说明("");
            lj临床路径版本.set状态(0);
        }
        lj临床路径版本.set路径ID(wayid);

        lj临床路径版本.set创建人("管理员");

        if (!StringUtils.isEmpty(tpl.get分组编码())) {
            lj临床路径版本.set病种编码(tpl.get分组编码());
        }


        Map<String, KeyVal> 内外科正则 = FormWordService.内外科正则;


        if (!StringUtils.isEmpty(tpl.get分组编码())) {
            //lj临床路径版本.set场合(tpl.get分组编码().substring(tpl.get分组编码().length()-1));
            for (Map.Entry<String, KeyVal> entry : 内外科正则.entrySet()) {
                if (Pattern.matches(entry.getValue().getK1().toString(), tpl.get分组编码())) {
                    lj临床路径版本.set场合(entry.getKey());
                    lj临床路径版本.set版本号(entry.getValue().getK2().toString());
                }
            }
        }
        if (isNew2) {
            LJ临床路径版本Dao.insert(lj临床路径版本);
        } else {
            // LJ临床路径版本Dao.updateById(lj临床路径版本);
        }


        return RpnMsg.SUCCESS(tpl.getId());
    }

    @PostMapping("import-tpl")
    public RpnMsg importTpl(@RequestBody Map<String, Object> map) throws Exception {
        PathTpl tpl = new PathTpl();
        org.apache.commons.beanutils.BeanUtils.populate(tpl, (Map) map.get("tpl"));
        List<Map<String, Object>> metasMap = (List<Map<String, Object>>) map.get("metas");
        String ctime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        List<PathTplMeta> metas = new ArrayList<>();
        for (Map<String, Object> map1 : metasMap) {
            PathTplMeta meta = new PathTplMeta();
            org.apache.commons.beanutils.BeanUtils.populate(meta, map1);
            metas.add(meta);
        }
        LJ临床路径版本 lj临床路径版本 = LJ临床路径版本Dao.selectById(tpl.getId());
        boolean isNew2 = (lj临床路径版本 == null);
        if (lj临床路径版本 != null) {
            return RpnMsg.FAIL("模板[" + lj临床路径版本.get版本说明() + "]已经存在!");
        }

        List<PathTplData> data = new ArrayList<>();
        List<String> proNames = new ArrayList<>();
        List<Map<String, Object>> dataMap = (List<Map<String, Object>>) map.get("data");
        for (Map<String, Object> map1 : dataMap) {
            PathTplData d = new PathTplData();
            org.apache.commons.beanutils.BeanUtils.populate(d, map1);
            if (!StringUtils.isEmpty(d.getName())) {
                proNames.add(d.getName());
            }
            if (!StringUtils.isEmpty(d.getProSubType())) {
                proNames.add(d.getProSubType());
            }
            data.add(d);
        }

        tpl.set最近修改日期(ctime);
        tpl.setId(UUID.randomUUID().toString());
        tpl.set创建日期(ctime);
        pathTplDao.insert(tpl);
        for (PathTplMeta meta : metas) {
            meta.set模板ID(tpl.getId());
            pathTplMetaDao.insert(meta);
        }
        for (PathTplData datum : data) {
            datum.set模板ID(tpl.getId());
            pathTplDataDao.insert(datum);
        }
        //=============以下为杨波需要处理的数据========
        //1.通过疾病编码获取路径ID
        Integer wayid = 0;
        if (!StringUtils.isEmpty(tpl.get路径ID())) {
            wayid = Integer.parseInt(tpl.get路径ID());
        }
        List<Clinicalpathwaydetail> clinicalpathwaydetails = new TreeList();
        for (PathTplData datum : data) {
            Clinicalpathwaydetail detail = new Clinicalpathwaydetail();
            detail.setId(UUID.randomUUID().toString());
            detail.set路径ID(wayid);
            detail.set序号(datum.getXh());
            detail.set小分类(datum.getProSubType());
            detail.set版本ID(tpl.getId());
            detail.set备注(datum.getMark());
            detail.set执行性质((datum.getRqd() == null || datum.getRqd() == false) ? 0 : 1);
            detail.set名称(datum.getName());
            detail.set大分类(datum.getProType());
            detail.set项目id(datum.getObjid());
            clinicalpathwaydetails.add(detail);
        }
        for (int i = 0; i < clinicalpathwaydetails.size(); i++) {
            clinicalpathwaydetails.get(i).set序号(i + 1);
            if (StringUtils.isEmpty(clinicalpathwaydetails.get(i).get项目id())) {
                clinicalpathwaydetails.get(i).set项目id("none");
                continue;
            }
            clinicalpathwaydetailDao.insert(clinicalpathwaydetails.get(i));
        }
        lj临床路径版本 = new LJ临床路径版本();
        lj临床路径版本.setId(tpl.getId());
        lj临床路径版本.set创建时间(new Date());
        lj临床路径版本.set标准床日(0);
        lj临床路径版本.set标准金额(0.0);
        lj临床路径版本.set版本号("标准版本");
        lj临床路径版本.set版本说明("");
        lj临床路径版本.set状态(0);
        lj临床路径版本.set路径ID(wayid);
        lj临床路径版本.set创建人("管理员");
        if (!StringUtils.isEmpty(tpl.get分组编码())) {
            lj临床路径版本.set病种编码(tpl.get分组编码());
        }
        Map<String, KeyVal> 内外科正则 = FormWordService.内外科正则;
        if (!StringUtils.isEmpty(tpl.get分组编码())) {
            for (Map.Entry<String, KeyVal> entry : 内外科正则.entrySet()) {
                if (Pattern.matches(entry.getValue().getK1().toString(), tpl.get分组编码())) {
                    lj临床路径版本.set场合(entry.getKey());
                    lj临床路径版本.set版本号(entry.getValue().getK2().toString());
                }
            }
        }
        LJ临床路径版本Dao.insert(lj临床路径版本);
        System.out.println("导入完成！");
        return RpnMsg.SUCCESS();
    }

    @PostMapping("save_mbmx")
    public RpnMsg addMxToMb(@RequestBody Map<String, Object> map) {
        Map<String, Object> map1 = (Map<String, Object>) map.get("item");
        List<Map<String, Object>> tempIds = (List<Map<String, Object>>) map.get("template");
        if (tempIds.size() > 0 && map.get("isAdd") != null
                && "1".equals(map.get("isAdd").toString())) {
            tempIds = pathTplDataDao.getTempids(tempIds);
        }
        String tempnames = "";
        List<Map<String, Object>> pathIds = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < tempIds.size(); i++) {
            Map<String, Object> dt = (Map<String, Object>) tempIds.get(i);
            String tempid = dt.get("tempId").toString();
            String tempname = dt.get("tempName").toString();
            List<Clinicalpathwaydetail> lst =
                    clinicalpathwaydetailDao.getLcljmxbyXmid(tempid, map1.get("xmid").toString());
            if (lst.size() > 0) {
                tempnames += tempname + ',';
                continue;
            }
            List<PathTplData> pdl =
                    pathTplDataDao.getMaxxhBymbObjid(tempid, map1.get("xmid").toString());
            if (lst.size() > 0) {
                tempnames += tempname + ',';
                continue;
            }
            pathIds.add(dt);
        }
        for (int j = 0; j < pathIds.size(); j++) {
            Map<String, Object> dt = (Map<String, Object>) pathIds.get(j);
            String tempid = dt.get("tempId").toString();
            // 保存路径模板数据
            List<PathTplData> pdl = pathTplDataDao.getMaxxhBymbid(tempid, map1.get("type").toString());
            PathTplData pd = new PathTplData();
            if (pdl.size() > 0) {
                PathTplData pdt = (PathTplData) pdl.get(0);
                pathTplDataDao.updateXh(tempid, pdt.getXh());
                List<V临床路径项目> xmkl = LJ临床路径版本Dao.getljxm(map1.get("xmid").toString());
                if (xmkl.size() > 0) {
                    V临床路径项目 x = (V临床路径项目) xmkl.get(0);
                    pd.setId(UUID.randomUUID().toString());
                    pd.set模板ID(tempid);
                    pd.setProType(map1.get("type").toString());
                    pd.setXh(pdt.getXh() + 1);
                    pd.setObjid(map1.get("xmid").toString());
                    pd.setProSubType(x.get说明());
                    pd.setName(x.get名称());
                    pd.setRqd(pdt.getRqd());
                    pd.setTotal(0.0d);
                    pd.setMark("不判断");
                    pathTplDataDao.insert(pd);
                }
            }
            // 保存LJ_临床路径明细
            Clinicalpathwaydetail detail = new Clinicalpathwaydetail();
            List<Clinicalpathwaydetail> d = clinicalpathwaydetailDao.getLcljmx(tempid, map1.get("type").toString());
            if (d.size() > 0) {
                Clinicalpathwaydetail dtl = (Clinicalpathwaydetail) d.get(0);
                clinicalpathwaydetailDao.updateXh(tempid, dtl.get序号());
                String mbmxid = UUID.randomUUID().toString();
                detail.set序号(dtl.get序号() + 1);
                detail.setId(mbmxid);
                detail.set路径ID(dtl.get路径ID());
                detail.set版本ID(tempid);
                detail.set项目id(map1.get("xmid").toString());
                detail.set开始天数(dtl.get开始天数());
                detail.set结束天数(dtl.get结束天数());
                detail.set择期(dtl.get择期());
                detail.set备注("手动添加");
                detail.set执行性质(0);
                detail.set单价(Double.parseDouble(map1.get("dj").toString()));
                detail.set数量(Double.parseDouble(map1.get("sl").toString()));
                detail.set名称(map1.get("xmmc").toString());
                detail.set频率(0);
                clinicalpathwaydetailDao.insert(detail);
                //  插入LJ_临床路径明细从表
                LJ临床路径明细从表 从表 = new LJ临床路径明细从表();
                从表.setId(UUID.randomUUID().toString());
                从表.set明细id(mbmxid);
                从表.set单价(Double.parseDouble(map1.get("dj").toString()));
                //从表.set数量(Double.parseDouble(map1.get("sl").toString()));
                //从表.set金额(从表.get数量()*从表.get单价());
                从表.set模板id(tempid);
                从表.set缺省(false);
                lj临床路径明细从表Dao.insert(从表);
            }
        }
        if (pathIds.size() == 0) {
            return RpnMsg.FAIL("添加到模板失败，项目在模板中已存在");
        } else if (tempnames.length() > 0) {
            return RpnMsg.FAIL("添加到部分模板成功，未添加模板有：" + tempnames + "原因：项目已存在");
        } else {
            return RpnMsg.SUCCESS("项目添加到模板成功！");
        }
    }

    @Autowired
    MyProperties myProperties;

    @GetMapping("version")
    public RpnMsg version() {
        return RpnMsg.SUCCESS(myProperties.getSoftVersion());
    }

    @Autowired
    LJ临床路径版本Dao lj临床路径版本Dao;

    @GetMapping("ljdir")
    public RpnMsg ljdir(@RequestParam(defaultValue = "") String s) {
        List<Map<String, Object>> list = lj临床路径版本Dao.V临床路径目录(s);
        return RpnMsg.SUCCESS(list);
    }

    @Autowired
    CommonDao commonDao;

    @PostMapping("drug-instru")
    public RpnMsg drugInstru(@RequestBody List<String> ls) {
        List<Map<String, Object>> 药品说明 = commonDao.药品说明(ls);
        return RpnMsg.SUCCESS(药品说明);
    }


    @Value("${upload-path}")
    private String uploadPath;


    @PostMapping("destory-file")
    public RpnMsg destoryFile(String f) {
        String fPath = uploadPath + "/files/" + f;
        try {
            boolean b = Files.deleteIfExists(Paths.get(fPath));
        } catch (Exception ex) {
            return RpnMsg.FAIL(ex.getMessage());
        }
        return RpnMsg.SUCCESS();
    }

    @PostMapping("ls-files")
    public RpnMsg LsFiles(String tpl) {
        String[] ls = tpl.split(",");
        List<JSONObject> fs = new ArrayList<JSONObject>();

        for (String l : ls) {
            String tPath = uploadPath + "/files/" + l;
            if (!Files.exists(Paths.get(tPath))) {
                continue;
            }
            File file = Paths.get(tPath).toFile();
            List<String> ts = Arrays.stream(file.listFiles()).map(it -> it.getName()).collect(Collectors.toList());
            for (String t : ts) {
                JSONObject o = new JSONObject();
                o.put("name", t);
                o.put("url", l + "/" + t);
                fs.add(o);
            }
        }
        return RpnMsg.SUCCESS(fs);
    }

    @PostMapping("list-files")
    public RpnMsg getFilesList(String name) {
        String tPath = uploadPath + "/files/";
        List<JSONObject> fs = new ArrayList<JSONObject>();
        File file = Paths.get(tPath).toFile();
        List<String> ts = Arrays.stream(file.listFiles()).map(it -> it.getName()).collect(Collectors.toList());
        for (String t : ts) {

            JSONObject o = new JSONObject();
            o.put("name", t);
            o.put("url", "/" + t);
            if (!"".equals(name) && t.indexOf(name) > 0) {
                fs.add(o);
            } else {
                fs.add(o);
            }
        }
        return RpnMsg.SUCCESS(fs);
    }

    @PostMapping("file-upload")
    public RpnMsg upload(
            @RequestParam("files") MultipartFile[] files, String tpl) {

        for (MultipartFile file : files) {
            String tPath = uploadPath + "/files/" + tpl;
            // 如果目录不存在则创建
            File uploadDir = new File(tPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            //String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = OriginalFilename;
            File localFile = new File(tPath + "/" + filename);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地

            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        String s = tpl.replaceAll("-路径表单", "").replaceAll("-路径方案", "");
        PathTpl tpl1 = pathTplDao.selectById(s);
        if (tpl1 == null) return RpnMsg.SUCCESS();
        tpl1.setUpload(true);
        pathTplDao.updateById(tpl1);

        return RpnMsg.SUCCESS();
    }

    /***
     * 1.验证是否变异，2.根据就诊号获取病人信息，保存路径变异信息
     * @param map
     * @return
     */
    @Autowired
    YB_Path_byqkDao ypbDao;

    @Autowired
    YB_Path_byyyDao pdyDao;

    @PostMapping("PathForm")
    public RpnMsg PathForm(@RequestBody Map<String, Object> map) {
        int tp = (int) map.get("tp");
        if (tp == 1) {
            String param = map.get("param").toString();
            // 验证路径是否变异
            List<Map<String, Object>> fs = commonDao.getPsthPatInfo(param);
            boolean r = false;
            for (Object l : fs) {
                JSONObject j = (JSONObject) l;
                if (!"".equals(j.get("入组错误1"))) {
                    r = true;
                    break;
                }
                if (!"".equals(j.get("费用2"))) {
                    r = true;
                    break;
                }
                if (!"".equals(j.get("床日3"))) {
                    r = true;
                    break;
                }
                if (!"".equals(j.get("是否超范围4"))) {
                    r = true;
                    break;
                }
            }
            return RpnMsg.SUCCESS(r);
        } else if (tp == 2) {
            String param = map.get("param").toString();
            // 根据就诊号获取病人信息
            return RpnMsg.SUCCESS(commonDao.getPsthPatInfo(param));
        } else if (tp == 3) {
            YB_Path_byqk ms = new YB_Path_byqk();
            ms.setBrid(map.get("jzh").toString());


            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 2.退出，4.完成
            ms.setPathzt(Integer.parseInt(map.get("status").toString()));
            if (ms.getPathzt() == 4) {
                ms.setSfby(Integer.parseInt(map.get("isMutation").toString()));
                try {
                    ms.setWcsj(sd.parse(map.get("time").toString()));
                    ms.setBysj(sd.parse(map.get("mutationTime").toString()));
                } catch (java.text.ParseException e) {
                    return RpnMsg.FAIL("时间不能为空或时间格式错误！");
                }
            }
            // 获取变异记录查询条件
            Map<String, Object> smp = new HashMap<>();
            smp.put("brid", ms.getBrid());
            // 如果已经存在则修改，否则保存路径变异信息
            List<YB_Path_byqk> ysls = ypbDao.selectByMap(smp);
            if (ysls.size() > 0) {
                ypbDao.updateById(ms);
            } else {
                ypbDao.insert(ms);
            }
            // 如果变异，插入变异原因
            if (ms.getSfby() == 1) {
                List<YB_Path_byqk> msls = ypbDao.selectByMap(smp);
                if (msls.size() > 0) {
                    YB_Path_byqk qk = (YB_Path_byqk) msls.get(0);
                    ArrayList<Integer> ss = (ArrayList<Integer>) map.get("reasons");
                    // 清除变异原因后重新插入
                    Map<String, Object> bmap = new HashMap<>();
                    bmap.put("byid", qk.getId());
                    pdyDao.deleteByMap(bmap);
                    // 重新插入
                    for (Integer i : ss) {
                        YB_Path_byyy by = new YB_Path_byyy();
                        by.setByid(qk.getId());
                        by.setByyyid(i);
                        by.setByyy("");
                        pdyDao.insert(by);
                    }
                } else {
                    return RpnMsg.FAIL("未获取到变异记录，未能添加异常原因");
                }
            }
            return RpnMsg.SUCCESS();
        } else if (tp == 4) {
            // 统计报表
            return RpnMsg.SUCCESS();
        }
        return RpnMsg.FAIL("参数错误");
    }
}



